package com.coin900.coin.server.fu.ctrl;

import com.coin900.coin.base.AjaxResponse;
import com.coin900.coin.base.FuConstants;
import com.coin900.coin.base.utils.FileUtils;
import com.coin900.coin.base.utils.GoogleAuthenticator;
import com.coin900.coin.persist.fu.FuUserAuthVO;
import com.coin900.coin.persist.fu.FuUserVO;
import com.coin900.coin.persist.sbi.SbiCityVO;
import com.coin900.coin.persist.sbi.SbiProvinceVO;
import com.coin900.coin.server.fu.form.FuUserForm;
import com.coin900.coin.server.fu.form.PwdForm;
import com.coin900.coin.service.fu.*;
import com.coin900.coin.service.sbi.ISbiCityService;
import com.coin900.coin.service.sbi.ISbiProvinceService;
import com.value.exception.BusinessException;
import com.value.utils.Md5Encoder;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shui
 * @create 2017-11-22
 **/
@Controller
public class FuUserCtrl extends FuController {

    /**
     * 跳转客户资料修改界面
     *
     * @param viewType
     * @param request
     * @return
     */
    @RequestMapping(value = "/info-modified", method = RequestMethod.GET)
    public ModelAndView infoModified(String viewType,
                                     HttpServletRequest request) {
        if (FuConstants.FU_PAGE.equals(viewType)) {
            ModelAndView mav = super.buildView(request, "project/info-modified");
            FuUserVO user = super.getUser();
            Map<String, Object> params = new HashMap<>();
            Long id = user.getId();
            params.put("id", id);
            params.put("dataStatus", 1);
            params.put("userStatus", 1);
            List<FuUserVO> fuUserVOS = this.userService.loadFuUser(params);

            params.clear();
            params.put("dataStatus", 1);
            List<SbiCityVO> sbiCityVOS = this.cityService.loadSbiCity(params);
            List<SbiProvinceVO> sbiProvinceVOS = this.provinceService.loadSbiProvince(params);

            mav.addObject("city", sbiCityVOS);
            mav.addObject("province", sbiProvinceVOS);
            mav.addObject("fuUserVO", fuUserVOS.get(0));
            return mav;
        }
        return null;
    }

    /**
     * 修改资料
     *
     * @param userForm
     * @param result
     * @param request
     * @return
     */
    @RequestMapping(value = "/user", method = RequestMethod.PATCH)
    public ModelAndView add(@Valid FuUserForm userForm,
                            BindingResult result,
                            HttpServletRequest request) {

        AjaxResponse response = super.buildAjaxResponse(request);
        FuUserVO user = super.getUser();
        Long id = user.getId();
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        params.put("dataStatus", 1);
        params.put("userStatus", 1);
        List<FuUserVO> fuUserVOS = this.userService.loadFuUser(params);
        if (fuUserVOS.isEmpty()) {
            throw new BusinessException("用户不存在");
        }

        user.setId(id);
        user.setPortrait(userForm.getPortrait());
        user.setProvinceId(userForm.getProvinceId());
        user.setCityId(userForm.getCityId());
        user.setGender(userForm.getGender());
        user.setProfession(userForm.getProfession());
        user.setWorkAddress(userForm.getWorkAddress());
        user.setMobile(userForm.getMobile());
        user.setQq(userForm.getQq());
        user.setEmail(userForm.getEmail());
        user.setModifiedInfor(user);
        user.setAddress(userForm.getAddress());
        String introduction = userForm.getIntroduction();
        if (!StringUtils.isBlank(introduction)) {
            user.setIntroduction(introduction);
        }
        this.userService.updateFuUser(user);
        // 更新 redis
        super.setUser(user);
        return response.getMav();
    }


    /**
     * 修改资料
     *
     * @param
     * @param request
     * @return
     */
    @RequestMapping(value = "/user-pwd", method = RequestMethod.GET)
    public ModelAndView pwd(String viewType,
                            HttpServletRequest request) {
        if (FuConstants.FU_PAGE.equals(viewType)) {
            ModelAndView mav = super.buildView(request, "user/password");
//            mav.addObject("oldPassword",getUser().getPassword());
            return mav;
        }
        AjaxResponse response = super.buildAjaxResponse(request);
        return response.getMav();
    }


    /**
     * 修改资料
     *
     * @param pwdForm
     * @param request
     * @return
     */
    @RequestMapping(value = "/user/pwd", method = RequestMethod.PATCH)
    public ModelAndView form(@RequestBody PwdForm pwdForm,
                             HttpServletRequest request) {
        AjaxResponse response = super.buildAjaxResponse(request);
        FuUserVO user = super.getUser();
        Long id = user.getId();
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        params.put("dataStatus", 1);
        params.put("userStatus", 1);
        List<FuUserVO> fuUserVOS = this.userService.loadFuUser(params);
        if (fuUserVOS.isEmpty()) {
            throw new BusinessException("用户不存在");
        }
        FuUserVO fuUserVO = fuUserVOS.get(0);
        if (StringUtils.isEmpty(pwdForm.getNewPassword())) {
            throw new BusinessException("请输入正确的新密码");
        }
        if (StringUtils.isEmpty(pwdForm.getOldPassword())) {
            throw new BusinessException("请输入正确的旧密码");
        }
        if (StringUtils.isEmpty(pwdForm.getRePassword())) {
            throw new BusinessException("请输入正确的密码");
        }

        String oldPassword = Md5Encoder.generateCode(pwdForm.getOldPassword());

        String newPassword = Md5Encoder.generateCode(pwdForm.getNewPassword());

        String rePassword = Md5Encoder.generateCode(pwdForm.getRePassword());

        if (!fuUserVO.getPassword().equals(oldPassword)) {
            throw new BusinessException("请输入正确的旧密码");
        }
        if (!newPassword.equals(rePassword)) {
            throw new BusinessException("二次输入的密码不一致");
        }

        user.setId(id);
        user.setPassword(newPassword);
        user.setModifiedInfor(getUser());
        this.userService.updateFuUser(user);
        // 更新 redis
        super.setUser(user);
        return response.getMav();
    }

    /**
     * 添加实名认证信息
     *
     * @param authVO
     * @param request
     * @return
     */
    @RequestMapping(value = "/user/auth", method = RequestMethod.POST)
    public ModelAndView auth(@RequestBody FuUserAuthVO authVO,
                             HttpServletRequest request) {

        AjaxResponse response = super.buildAjaxResponse(request);
        FuUserVO userVO = super.getUser();
        authVO.setUserId(userVO.getId());
        authVO.setCheckStatus(FuConstants.FU_CHECK_STATUS_ING);
        authVO.setCreatedInfor(userVO);

        if (authVO.getIdCardFacade() == null) {
            throw new BusinessException("请上传身份证正面照片");
        }

        if (authVO.getIdCardHandheld() == null) {
            throw new BusinessException("请上传手持身份证照片");
        }

        if (authVO.getIdCardReverse() == null) {
            throw new BusinessException("请上传身份证背面照片");
        }

        /**
         *
         * 身份证号码的校验
         */

        authVO.setCheckStatus(FuConstants.FU_CHECK_STATUS_ING);
        this.authService.insertFuUserAuth(authVO);
        return response.getMav();
    }

    /**
     * 谷歌设置
     *
     * @param
     * @param request
     * @return
     */
    @RequestMapping(value = "/user/google_setting", method = RequestMethod.GET)
    public ModelAndView google_setting(String viewType,HttpServletRequest request) {
        if(FuConstants.FU_PAGE.equals(viewType)){
            ModelAndView modelAndView = super.buildView(request, "user/google_setting");
            return modelAndView;
        }
        AjaxResponse response = super.buildAjaxResponse(request);
        return response.getMav();
    }



    /**
     * 生成谷歌验证绑定的二维码和秘钥
     *
     * @param
     * @param request
     * @return
     */
    @RequestMapping(value = "/user/build_google_secret", method = RequestMethod.GET)
    public ModelAndView build_google_secret(HttpServletRequest request) {
        AjaxResponse response = super.buildAjaxResponse(request);
        //获取当前的用户账号
        String secret = GoogleAuthenticator.generateSecretKey();
        FuUserVO user = getUser();
        String qrcode = GoogleAuthenticator.getQRBarcode(user.getUsername(), secret);
        //产生二维码
        String encode = FileUtils.encode(qrcode, 200, 200);
        //返回数据
        //修改用户的secret
        getSession().setAttribute("googleSecret",secret);
        Map<String,Object> map = new HashMap<>();
        map.put("qrcodeBase64",encode);
        map.put("secret",secret);
        System.out.println(secret);
        response.addModel(map);
        return response.getMav();
    }


    /**
     * 绑定谷歌
     *
     * @param
     * @param request
     * @return
     */
    @RequestMapping(value = "/user/bind_google_secret", method = RequestMethod.PATCH)
    public ModelAndView bind_google_secret(@RequestParam String secretCode, HttpServletRequest request) {
        AjaxResponse response = super.buildAjaxResponse(request);
        FuUserVO user = super.getUser();
        Long code;
        String googleSecret;
        try{
            code=Long.parseLong(secretCode);
            googleSecret=getSession().getAttribute("googleSecret").toString();
        }catch (Exception e){
            throw new BusinessException("请输入正确的验证码");
        }
        userService.doBindGoogleSecret(user,code,googleSecret);
        return response.getMav();
    }

    /**
     * 检查手机号是否存在
     *
     * @param mobile
     * @param request
     * @return
     */
    @RequestMapping(value = "/user/check_mobile", method = RequestMethod.GET)
    public ModelAndView check_mobile(@RequestParam String mobile,
                                     HttpServletRequest request) {
        AjaxResponse response = super.buildAjaxResponse(request);
        Map<String,Object> params = new HashMap<>();
        params.put("mobile",mobile);
        List<FuUserVO> fuUserVOS = userService.loadFuUser(params);
        if(fuUserVOS.isEmpty()){
            response.addObject("isExist",false);
        }else{
            response.addObject("isExist",true);
        }
        return response.getMav();
    }

    /**
     * 取消谷歌验证
     *
     * @param
     * @param request
     * @return
     */
    @RequestMapping(value = "/user/cancel_google_secret", method = RequestMethod.PATCH)
    public ModelAndView cancel_google_secret(@RequestParam  String secretCode, HttpServletRequest request) {
        AjaxResponse response = super.buildAjaxResponse(request);
        FuUserVO user = super.getUser();
        Long code;
        try{
            code=Long.parseLong(secretCode);
        }catch (Exception e){
            throw new BusinessException("请输入正确的验证码");
        }
        userService.doCancelGoogleSecret(user,code);
        return response.getMav();
    }

    @Autowired
    private IFuUserService userService;
    @Autowired
    private IFuUserAuthService authService;
    @Autowired
    private ISbiCityService cityService;
    @Autowired
    private ISbiProvinceService provinceService;
}
